After acquiring some experience from analyzing several traces in GTFS, I'd like to understand the structure of the Python standard module datetime.

1. datetime

The datetime module supplies classes for manipulating dates and times. Its subcalss relationships are listed below.

timedate
    date
    time
    tzinfo          # an abstract base class
        timezone
    datetime        # date + time

    timedelta

Their constructors are,

import datetime

datetime.date(year, month, day)
datetime.time(hour=0, minute=0, second=0, microsecond=0, tzinfo=None)
datetime.timezone(offset, name=None)    
# date + time
datetime.datetime(year, month, day, hour=0, minute=0, second=0, microsecond=0, tzinfo=None)

datetime.timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0)

# The datetime module exports the following constants
datetime.MINYEAR    # 1
datetime.MAXYEAR    # 9999

The differences between datetime and time modules, excerpt from difference between datetime vs time modules

the time module is principally for working with unix time stamps; expressed as a floating point number taken to be seconds since the unix epoch.

the datetime module can support many of the same operations, but provides a more object oriented set of types, and also has some limited support for time zones.

2. datetime.date

A datetime.date object represents a date (year, month and day) in the Gregorian calendar (公历).

import datetime

class datetime.date(year, month, day)

# An example
>>> datetime.date.today()           # It is equivalent to `datetime.datetime.now().date()`
datetime.date(2016, 11, 27)

2.1 Class and instance attributes

Class attributes

>>> datetime.date.min
datetime.date(1, 1, 1)          # date(MINYEAR, 1, 1)

>>> datetime.date.max
datetime.date(9999, 12, 31)     # date(MAXYEAR, 12, 31)

>>> datetime.date.resolution
datetime.timedelta(1)           # timedelta(days=1)

Instance attributes (read-only)

>>> d = datetime.date.today()
>>> d.year, d.month, d.day
(2016, 11, 27)

2.2 Supported operations

timedelta = date1 - date2       # return a `datetime.timedelta` object
date1 < date2
date2 = date1 + timedelta   
date2 = date1 - timedelta   

# Usage
>>> d1 = datetime.date(2013, 9, 10)
>>> d2 = datetime.date.today()
>>> d2 - d1
datetime.timedelta(1174)

2.3 class and instance methods

Class methods

date.today()                    # return the current local date. This is equivalent to `date.fromtimestamp(time.time())`
date.fromtimestamp(timestamp)   # return the local date corresponding to the POSIX timestamp
date.fromordinal(ordinal)       # return the date corresponding to the proleptic Gregorian ordinal

>>> import datetime, time
>>> datetime.date.fromtimestamp(time.time())
datetime.date(2016, 11, 27)
>>> date.fromordinal(2016*365 + 11*30 + 27)
datetime.date(2016, 8, 21)

Instance methods

d.replace(year=self.year, month=self.month, day=self.day)   # Return a date with the same value, except for those parameters given new values by whichever keyword arguments are specified. For example, `d.replace(day=26)`.

d.timetuple()                                               #  Return a `time.struct_time` such as returned by time.localtime(). It is equivalent to `time.struct_time((d.year, d.month, d.day, 0, 0, 0, d.weekday(), yday, -1))`.
>>> d = datetime.date.today(); d.timetuple()
time.struct_time(tm_year=2016, tm_mon=11, tm_mday=27, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=6, tm_yday=332, tm_isdst=-1)

d.toordinal()                                               # Return the proleptic Gregorian ordinal of the date.
>>> d = datetime.date.today(); d.toordinal()
736295

date.weekday()                                              # Return the day of the week as an integer, where Monday is 0 and Sunday is 6. For example, date(2002, 12, 4).weekday() == 2, a Wednesday. See also isoweekday().
date.isoweekday()                                           # Return the day of the week as an integer, where Monday is 1 and Sunday is 7. 
d.isocalendar()                                             # Return a 3-tuple, (ISO year, ISO week number, ISO weekday) where a week starts on a Monday and ends on a Sunday.
# Examples
>>> d = datetime.date.today() # Sunday
>>> d.weekday()
6
>>> d.isoweekday()
7
>>> d.isocalendar()
(2016, 47, 7)
>>> date(2003, 12, 29).isocalendar()    # 2003-12-29 is Monday
(2004, 1, 1)
>>> date(2004, 1, 1).isocalendar()      # 2004-1-4 is Thursday
(2004, 1, 4)

d.isoformat()                                               # Return a string representing the date in ISO 8601 format, ‘YYYY-MM-DD’. 
d.__str__()                                                 # str(d) is equivalent to d.isoformat().
>>> d = datetime.date.today(); d.isoformat()
'2016-11-27'

d.ctime()                                                   # Return a string representing the date. `d.ctime()` is equivalent to `time.ctime(time.mktime(d.timetuple()))` on platforms where the native C ctime() function conforms to the C standard.
>>> d = datetime.date.today(); d.ctime()
'Sun Nov 27 00:00:00 2016'

d.strftime(format)                                          # Return a string representing the date, controlled by an explicit format string. 
d.__format__(format)                                        # Same as `date.strftime()`.

For a complete list of formatting directives, see strftime() and strptime() Behavior.

3. datetime.time

A datetime.time object represents a (local) time of day and subject to adjustment via a datetime.tzinfo object.

import datetime

class datetime.time(hour=0, minute=0, second=0, microsecond=0, tzinfo=None, *, fold=0)

# An example
>>> import datetime
>>> datetime.datetime.now().time()
datetime.time(18, 15, 4, 629299)

4. datetime.timezone

tzinfo is an abstract base class. One of its subclasses is timezone, each instance of which represents a timezone defined by a fixed offset from UTC (Coordinated Universal Time).

datetime.timezone(offset, name=None)    # -timedelta(hours=24) <= offset <= timedelta(hours=24), minute resolution, representing the difference between the local time and UTC.

# An example
>>> datetime.timezone(datetime.timedelta(hours=3, minutes=30))
datetime.timezone(datetime.timedelta(0, 12600))

5. datetime.datetime

A datetime.datetime object is a single object containing all the information from a datetime.date object and a datetime.time object.

import datetime

class datetime.datetime(year, month, day, hour=0, minute=0, second=0, microsecond=0, tzinfo=None, *, fold=0)

classmethod datetime.today()        # Return the current local datetime, with tzinfo None.
classmethod datetime.now(tz=None)   # Return the current local datetime with a given tz. 
classmethod datetime.utcnow()       # Return the current UTC (Coordinated Universal Time) date and time

# An example
>>> dt = datetime.datetime.now()
>>> dt.date()
datetime.date(2016, 11, 27)
>>> dt.time()
datetime.time(18, 24, 3, 491584)

6. datetime.timedelta

A timedelta object represents a duration, the difference between two dates or times. Refer to my previous post Python使用笔记:时间的运算timedelta.

datetime.datetime.timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0)

# Class attributes
>>> datetime.timedelta.min
datetime.timedelta(-999999999)                  # timedelta(days=-999999999)

>>> datetime.timedelta.max
datetime.timedelta(999999999, 86399, 999999)    # timedelta(days=999999999, hours=23, minutes=59, seconds=59, microseconds=999999)

>>> datetime.timedelta.resolution
datetime.timedelta(0, 0, 1)                     # timedelta(microseconds=1)

7. strftime() and strptime() Behavior

The subclasses of the module datetime, date, datetime, and time all support a strftime(format) method, to create a string representing the time under the control of an explicit format string.

import datetime

# Instance methods
datetime.date.strftime(format)
datetime.time.strftime(format)
datetime.datetime.strftime(format)

# Examples
>>> dt = datetime.datetime.today()      # datetime.datetime(2016, 11, 27, 22, 21, 55, 506768)
>>> dt.date().strftime('%y-%m-%d')      # datetime.date(2016, 11, 27)
'16-11-27'
>>> dt.time().strftime('%H:%M:%S')      # datetime.time(22, 21, 55, 506768)
'22:21:55'
>>> dt.strftime('%y-%m-%d %H:%M:%S')
'16-11-27 22:21:55'

Conversely, the datetime.strptime() class method creates a datetime object from a string representing a date and time and a corresponding format string.

import datetime

datetime.datetime.strptime(date_string, format)  # Return a datetime

# An example
>>> datetime.datetime.strptime('2016-11-27 22:14:21', '%Y-%m-%d %H:%M:%S')
datetime.datetime(2016, 11, 27, 22, 14, 21)

A list of all the format codes are listed here.

8. dateutil

The module dateutil provides powerful extensions to datetime module.

References:

[1] Python Documentation: datetime — Basic date and time types

本文系Spark & Shine原创,转载需注明出处本文最近一次修改时间 2022-03-17 20:41

results matching ""

    No results matching ""